package controller

import (
	"encoding/json"
	"miao/dto"
	"miao/service"
	"miao/util"
	"net/http"

	"github.com/gin-gonic/gin"
)

func Login(c *gin.Context) {
	b, _ := c.GetRawData()

	dto := dto.LoginDTO{}
	//测试直接使用dto
	_ = json.Unmarshal(b, &dto)
	if dto.Username == "" || dto.Password == "" {
		c.JSON(http.StatusBadRequest, util.Fail(400, "用户名或密码不能为空"))
		return
	}
	result := service.Login(dto)
	if result.Code != 200 {
		c.JSON(http.StatusUnauthorized, util.Fail(401, result.Message))
		return
	}
	c.JSON(http.StatusOK, util.Success(result.Data))
}

func Register(c *gin.Context) {
	b, _ := c.GetRawData()

	dto := dto.LoginDTO{}
	//测试直接使用dto
	_ = json.Unmarshal(b, &dto)
	if dto.Username == "" || dto.Password == "" {
		c.JSON(http.StatusBadRequest, util.Fail(400, "用户名或密码不能为空"))
		return
	}
	result := service.Register(dto)
	if result.Code != 200 {
		c.JSON(http.StatusUnauthorized, util.Fail(401, result.Message))
		return
	}
	c.JSON(http.StatusOK, util.Success(result.Data))
}

func Info(c *gin.Context) {
	result := service.GetInfo()
	c.JSON(http.StatusOK, result)
}
